package com.example.demo;

import com.example.demo.messager.MessageReceiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.UUID;

@SpringBootApplication
public class Application implements CommandLineRunner {

	private static Logger LOGGER = LoggerFactory.getLogger(Application.class);
	public static final String SERVER_NAME_ID;

	static {
		SERVER_NAME_ID = declareServiceName();
		LOGGER.info("初始化服务名称,  当前发送提交服务名称:{}", SERVER_NAME_ID);
	}

	public static void main(String[] args) throws Exception {
		SpringApplication.run(Application.class, args);
		init();
		LOGGER.info("结束启动");
	}

	private static void init() {
		LOGGER.info("监听发送队列");
		registerToMq();
		LOGGER.info("初始化完成");
	}

	//申明一个服务ID，放在缓存中,并保存在数据库中
	private static String declareServiceName() {
		return ((UUID.randomUUID().toString() + System.currentTimeMillis()).hashCode() + "").substring(1);
	}

	private static void registerToMq() {
		final long timeInterval = 1000;
		new Thread(() -> {
			while (true) {
				LOGGER.info("=====检测MQ队列是否异常======");
				try {
					Thread.sleep(timeInterval);
					MessageReceiver.handler();
				} catch (InterruptedException e) {
					LOGGER.error("MQ 监控队列异常", e);
				}
			}
		}).start();
	}

	@Bean
	@Primary
	@ConfigurationProperties("saas.datasource")
	public DataSource saasDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean
	public EntityManagerFactory entityManagerFactory() {

		HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
		vendorAdapter.setGenerateDdl(true);
		vendorAdapter.setShowSql(true);
		vendorAdapter.setDatabase(Database.MYSQL);

		LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
		factory.setJpaVendorAdapter(vendorAdapter);
		factory.setPackagesToScan("com.example.demo.entity.**");
		factory.setDataSource(saasDataSource());
		factory.afterPropertiesSet();
		return factory.getObject();
	}

	@Override
	public void run(String... strings) {
		System.out.println("Hello, Spring Boot gives many options ;)");
	}

}
